import React, { useState, useEffect } from 'react';
import '../../style/playlist.css';
import axios from 'axios';
import { Link } from 'react-router-dom';

// 单个歌单卡片组件
const PlaylistCard = ({ playlist }) => (
    <div className="playlist-card">
        <img src={playlist.coverImgUrl} alt={playlist.name} />
        <div className="play-logo">
            <i className="ri-play-fill"></i>
        </div>
        <div className="playlist-info">
            <span className="playlist-count">{(playlist.playCount / 10000).toFixed(1)}万</span>
            <p className="playlist-name">{playlist.name}</p>
            <p className="playlist-creator">{playlist.creator.nickname}</p>
        </div>
    </div>
);

// 歌单卡片容器
const PlaylistContainer = ({ playlists }) => (
    <div className="playlist-frame">
        {playlists.length > 0 ? (
            playlists.map((playlist) => (
                <Link to={playlist.id}><PlaylistCard key={playlist.id} playlist={playlist} /></Link>
            ))
        ) : (
            <p className="no-playlist">暂无数据</p>
        )}
    </div>
);

// 歌单分类组件
const PlaylistCategories = ({ selectedCategory, onCategoryClick }) => {
    const categories = ["全部", "流行", "说唱", "国风", "私藏", "电子", "摇滚", "轻音乐"];

    return (
        <div className="playlist-categories">
            {categories.map(category => (
                <div
                    key={category}
                    className={`category-item ${selectedCategory === category ? 'selected' : ''}`}
                    onClick={() => onCategoryClick(category)}
                >
                    {category}
                </div>
            ))}
        </div>
    );
};

// 主组件
const Playlist_Categories = () => {
    const [selectedCategory, setSelectedCategory] = useState("全部");
    const [playlists, setPlaylists] = useState([]);

    // 获取精品歌单
    const fetchPlaylists = async (category) => {
        try {
            const response = await axios.get('http://localhost:3000/top/playlist/highquality', {
                params: {
                    cat: category === "全部" ? undefined : category,
                    limit: 50
                }
            });
            setPlaylists(response.data.playlists || []);
        } catch (error) {
            console.error('Failed to fetch playlists:', error);
        }
    };

    useEffect(() => {
        fetchPlaylists(selectedCategory);
    }, [selectedCategory]);

    const handleCategoryClick = (category) => {
        setSelectedCategory(category);
    };

    return (
        <div className="playlist-container">
            <PlaylistCategories selectedCategory={selectedCategory} onCategoryClick={handleCategoryClick} />
            <h2 className="playlist-title">精品歌单</h2>
            <PlaylistContainer playlists={playlists} />
        </div>
    );
};

export default Playlist_Categories;